import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css' 
import App from './App.vue'
import router from './router/index'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import store from './store'
import axiosInstance from './utils/requests.js'

const app = createApp(App)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}

// 从localStorage加载用户信息
const token = localStorage.getItem('token')
const userType = localStorage.getItem('userType') || 'user'
const username = localStorage.getItem('username') || ''

if (token) {
  // 先设置axios的请求头，用于验证token
  axiosInstance.defaults.headers.Authorization = `Bearer ${token}`
  
  // 尝试验证token是否有效
  axiosInstance.get('/api/user/info/', { timeout: 2000 }) // 设置较短的超时时间
    .then(response => {
      // token有效，设置用户信息
      const userData = response.data?.data
      if (userData) {
        // 使用从API获取的最新用户信息
        store.commit('user/SET_USER', {
          username: userData.username,
          userType: userData.user_type === 'admin' || userData.user_type === 'ADMIN' ? 'admin' : 'user',
          id: userData.id
        })
      } else {
        // 没有获取到用户数据但请求成功，使用本地存储的用户信息
        store.commit('user/SET_USER', { userType, username })
      }
      store.commit('user/SET_AUTH', { isAuthenticated: true, token })
    })
    .catch(error => {
      // token无效或请求失败，清除用户状态
      console.error('Token验证失败或请求超时:', error)
      store.commit('user/CLEAR_USER')
      localStorage.removeItem('token')
      localStorage.removeItem('userType')
      localStorage.removeItem('username')
    })
} else {
  // 没有token，确保用户状态为未登录
  store.commit('user/CLEAR_USER')
}

app.use(ElementPlus)
app.use(router)
app.use(store)
app.mount('#app')